package com.buli.blmall.admin.system.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buli.blmall.admin.common.domain.SysLoginUser;
import com.buli.blmall.admin.core.horder.LoginUserHolder;
import com.buli.blmall.admin.system.entity.SysMenu;
import com.buli.blmall.admin.system.entity.SysRoleMenu;
import com.buli.blmall.admin.system.entity.SysUserRole;
import com.buli.blmall.admin.system.mapper.SysRoleMenuMapper;
import com.buli.blmall.admin.system.mapper.SysUserRoleMapper;
import com.buli.blmall.admin.system.vo.SysMenuVO;
import com.buli.blmall.admin.system.mapper.SysMenuMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.bean.BeanUtil;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单 服务类
 * </p>
 *
 * @author buli
 * @since 2025-02-27
 */
@Slf4j
@Service
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 查询菜单详情
     *
     * @param id
     * @return 菜单详情
     */
    public SysMenuVO info(Long id) {
        return BeanUtil.copyProperties(getById(id), SysMenuVO.class );
    }

    /**
     * 查询菜单集合
     *
     * @param sysMenuVo
     * @return 菜单集合
     */
    public List<SysMenuVO> queryList(SysMenuVO sysMenuVo) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysMenu::getMenuType, "C", "M");
        if (sysMenuVo.getMenuName() != null) {
            queryWrapper.like(SysMenu::getMenuName, sysMenuVo.getMenuName());
        }
        SysLoginUser sysLoginUser = LoginUserHolder.get();
        //非管理员
        if (!sysLoginUser.getUserDetail().getUsername().equals("admin")) {
            //获取用户角色
            LambdaQueryWrapper<SysUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
            userRoleQueryWrapper.eq(SysUserRole::getUserId, sysLoginUser.getUserDetail().getId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(userRoleQueryWrapper);
            //获取角色菜单
            LambdaQueryWrapper<SysRoleMenu> roleMenuQueryWrapper = new LambdaQueryWrapper<>();
            roleMenuQueryWrapper.in(SysRoleMenu::getRoleId, sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
            //获取菜单信息
            List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(roleMenuQueryWrapper);
            queryWrapper.in(SysMenu::getMenuId, sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList()));
        }
        //构建菜单树
        return buildMenuTree(BeanUtil.copyToList(list(queryWrapper), SysMenuVO.class));
    }

    private List<SysMenuVO> buildMenuTree(List<SysMenuVO> sysMenuVOS) {
        return sysMenuVOS.stream()
                .filter(menu -> menu.getParentId().equals(0L))
                .peek(menu -> menu.setChildren(getChildren(menu, sysMenuVOS)))
                .sorted(Comparator.comparingInt(SysMenuVO::getOrderNum))
                .collect(Collectors.toList());
    }

    private List<SysMenuVO> getChildren(SysMenuVO menu, List<SysMenuVO> sysMenuVOS) {
        return sysMenuVOS.stream()
                .filter(m -> m.getParentId().equals(menu.getMenuId()))
                .peek(m -> m.setChildren(getChildren(m, sysMenuVOS)))
                .sorted(Comparator.comparingInt(SysMenuVO::getOrderNum))
                .collect(Collectors.toList());
    }


    /**
     * 新增菜单
     * @param sysMenuVo
     * @return boolean
     */
    public boolean add(SysMenuVO sysMenuVo) {
        SysMenu sysMenu = BeanUtil.copyProperties(sysMenuVo, SysMenu.class );
        return save(sysMenu);
    }

    /**
     * 编辑菜单
     * @param sysMenuVo
     * @return boolean
     */
    public boolean edit(SysMenuVO sysMenuVo) {
        SysMenu sysMenu = BeanUtil.copyProperties(sysMenuVo, SysMenu.class );
        return updateById(sysMenu);
    }

    /**
     * 删除菜单
     * @param id
     * @return boolean
     */
    public boolean delete(Long id) {
        return removeById(id);
    }

    /**
     * 查询菜单集合
     * @param roleIds
     * @return
     */
    public List<SysMenu> getListByIds(List<Long> roleIds) {
        return baseMapper.selectBatchIds(roleIds);
    }

    /**
     * 带条件的分页查询
     * @param current
     * @param size
     * @param sysMenuVo
     * @return
     */
    public IPage<SysMenu> queryPageWithCondition(int current, int size, SysMenuVO sysMenuVo) {
        Page<SysMenu> page = new Page<>(current, size);
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        if (sysMenuVo != null) {
            // 示例：根据名称查询
            if (StringUtils.isNotBlank(sysMenuVo.getMenuName())) {
                queryWrapper.like(SysMenu::getMenuName, sysMenuVo.getMenuName());
            }
        }
        return this.page(page, queryWrapper);
    }

}
